//导入需要的包
const express = require('express');
const cors = require('cors');
const joi = require('@hapi/joi');
const expressJwt =  require('express-jwt')
const config = require('./config')
const path = require('path')


const app = express();

//二次封装 res.send() method
app.use((req, res, next) => {
  //err : 错误 
  //status : 状态 (默认1)
  res.cc = (err,status = 1)=>{
    res.send({
      status,
      message : err instanceof Error ? err.message : err
    })
  }
  next();
})

//跨域
app.use(cors());

//数据解析中间件
app.use(express.urlencoded({extended:false}));

//静态托管中间件
app.use("/upload",express.static(path.join(__dirname,"./upload")))

//解析token的中间件
app.use(expressJwt({ secret: config.secretKey }).unless({ path: [/^\/api\//] }))

//路由模块
const router = require('./router/user');
const routerUserInfo = require("./router/userInfo")
const routerArtcate = require("./router/artcate")
const routerArticle = require("./router/article")
app.use("/api",router)
app.use("/my",routerUserInfo) //以my开头的 需要token验证
app.use("/my/article",routerArtcate)
app.use("/my/article",routerArticle)

//错误中间件` 
app.use((err, req, res,next) => {


  if (err instanceof joi.ValidationError) return res.cc(err);

  if (err.name == 'UnauthorizedError') return res.cc('身份认证失败！');

  res.cc(err);
  

  next()
})

app.listen(3000, () => {
  console.log('http://localhost:3000');
});